using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using System.Collections.Concurrent;

namespace BF
{
    [System.Obsolete("", true)]
    public class Loom : MonoBehaviour
    {
        private static Loom instance;

        private static readonly object _lock = new object();
        private static readonly List<Action> _actions = new List<Action>();
        private static readonly List<Action> _temp = new List<Action>();

        public static void QueueOnMainThread(Action action)
        {
            lock (_lock)
            {
                _actions.Add(action);
            }
        }

        public static void QueueOnMainThread(Action action, float delay)
        {
            if (delay <= 0.001f)
            {
                QueueOnMainThread(action);
            }
            else
            {
                QueueOnMainThread(DelayAction(action, delay));
            }
        }

        static Loom()
        {
            instance = new GameObject("Loom").AddComponent<Loom>();
            DontDestroyOnLoad(instance.gameObject);
        }


        private void Awake()
        {
            if (instance != null && instance != this)
            {
                Destroy(this.gameObject);
            }
        }

        private void Update()
        {
            lock (_lock)
            {
                _temp.Clear();
                _temp.AddRange(_actions);
                _actions.Clear();
            }
            foreach (var action in _temp)
            {
                action?.Invoke();
            }
        }

        private static Action DelayAction(Action action, float delay)
        {
            return () => Timer.Pop()
                            .Delay(delay)
                            .Action(action)
                            .Execute();
        }
    }
}
